package com.demo.infrastructure.adapter;

import com.demo.domain.adapter.IWeiXinPort;
import com.demo.domain.model.WeiXinNoticeFunctionRequest;
import com.demo.domain.model.WeiXinNoticeFunctionResponse;
import com.demo.infrastructure.gateway.IWeiXinApiService;
import com.demo.infrastructure.gateway.dto.WeiXinTemplateMessageDTO;
import com.demo.infrastructure.gateway.dto.WeiXinTokenResponseDTO;
import com.demo.types.properties.WeiXinApiProperties;
import com.google.common.cache.Cache;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import retrofit2.Call;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 发送消息 方法主体
 */
@Slf4j
@Component
public class WeiXiPort implements IWeiXinPort {
    @Resource
    private WeiXinApiProperties properties;
    @Resource
    private IWeiXinApiService weiXinApiService;
    //<appid,accessToken> 存储当前accessToken
    @Resource
    private Cache<String, String> weixinAccessToken;

    /**
     * 发送微信通知
     * @param request
     * @return
     * @throws IOException
     */
    @Override
    public WeiXinNoticeFunctionResponse weiXinNotice(WeiXinNoticeFunctionRequest request) throws IOException {
        // 1. 获取 accessToken
        String accessToken = weixinAccessToken.getIfPresent(properties.getAppid());
        if (accessToken == null) {
            //获取accessToken
            Call<WeiXinTokenResponseDTO> call = weiXinApiService.getToken("client_credential", properties.getAppid(), properties.getAppsecret());
            WeiXinTokenResponseDTO res = call.execute().body();
            assert res != null;
            accessToken = res.getAccess_token();
            weixinAccessToken.put(properties.getAppid(), accessToken);
        }
        // 2. 发送模板消息
        HashMap<String, Map<String, String>> data = new HashMap<>();
        WeiXinTemplateMessageDTO msg = new WeiXinTemplateMessageDTO(properties.getTouser(), properties.getTemplate_id());
        WeiXinTemplateMessageDTO.put(data, WeiXinTemplateMessageDTO.TemplateKey.platform, request.getPlatform());
        WeiXinTemplateMessageDTO.put(data, WeiXinTemplateMessageDTO.TemplateKey.subject, request.getSubject());
        WeiXinTemplateMessageDTO.put(data, WeiXinTemplateMessageDTO.TemplateKey.description, request.getDescription());
        msg.setData(data);
        msg.setUrl(request.getJumpUrl());
        //发送
        Call<Void> call = weiXinApiService.sendMessage(accessToken, msg);
        call.execute();
        //3、res
        WeiXinNoticeFunctionResponse res = new WeiXinNoticeFunctionResponse();
        res.setSuccess(true);
        return res;
    }
}
